//
//  MILHomePageViewController.m
//  MicrowaveInteractionLight
//
//  Created by maple on 2016/12/14.
//  Copyright © 2016年 maple. All rights reserved.
//

#import "MILHomePageViewController.h"
#import "MILSettingViewController.h"
#import "MILSenceModeViewController.h"
#import "MILLightsSettingViewController.h"
#import "MILHomePageCollectionViewCell.h"
#import "MILSelectedDeviceViewController.h"
#import "MILRadarWarningViewController.h"
#import "GetUserDeviceApi.h"
#import <SystemConfiguration/CaptiveNetwork.h>
#import "SDCycleScrollView.h"
#import "PublicGetADListApi.h"
#import "SetModeApi.h"


@interface MILHomePageViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UIScrollViewDelegate,SDCycleScrollViewDelegate>
@property(nonatomic,strong)NSMutableArray *myDataArray;
@property (weak, nonatomic) IBOutlet UICollectionView *myCollectionView;
@property (weak, nonatomic) IBOutlet UIButton *myWarnBtn;
@property (weak, nonatomic) IBOutlet UIButton *myStatusBtn;
@property (weak, nonatomic) IBOutlet UIView *topView;

@property (weak, nonatomic) IBOutlet UIButton *myLeaveHomeBtn;
@property (weak, nonatomic) IBOutlet UIImageView *myScrollImageView1;
@property (weak, nonatomic) IBOutlet UIImageView *myScrollImageView2;
@property (weak, nonatomic) IBOutlet UIImageView *myScrollImageView3;
@property(strong,nonatomic)NSMutableArray *myDataMutableArray;//设备列表
@property(strong,nonatomic)SDCycleScrollView *cycleScrollView;//轮播图

@end

@implementation MILHomePageViewController


#pragma mark --  UI
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    //初始化UI
    [self initMILHomePageView];
    
    [self loadADImageView];
    
   

}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    //获取设备列表
    [self getUserDeviceList];
    
    [self checkHomeState];
}

- (void)refreshBaseControlValue
{
    [self setNavigationBarTitle:@"黑炎科技"];
    self.navigationBar.backgroundColor = [UIColor blackColor];
    [self setLeftButtonImage:[UIImage imageNamed:@"logoBottom"]];
//    self.view.backgroundColor = [UIColor colorWithRed:243/255.0 green:243/255.0 blue:243/255.0 alpha:1];
    
}


- (void)loadADImageView{
    PublicGetADListApi *api = [[PublicGetADListApi alloc] init];
    [api startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
        NSDictionary *dic = [request responseJSONObject];
        if ([dic[@"errcode"] intValue] == 0) {
            NSArray *array = dic[@"data"];
            NSString *domain = dic[@"domain"];
            NSMutableArray *data = [[NSMutableArray alloc] init];
            for (NSString *string in array) {
                NSString *urlString = [NSString stringWithFormat:@"%@/%@",domain,string];
                [data addObject:urlString];
            }
            [self.cycleScrollView setImageURLStringsGroup:data];
        }

    } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
        [SVProgressHUD showErrorWithStatus:request.responseJSONObject[@"errmsg"]];
    }];
}


- (void)initMILHomePageView
{
    [self.cycleScrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.topView);
    }];
    //2秒后弹框
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        UIView *myView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH*0.8, 106+50+21)];
//        
//        UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake((myView.frame.size.width - 97)/2, 0, 97, 106)];
//        imageView.image = [UIImage imageNamed:@"radarWarn"];
//        [myView addSubview:imageView];
//        
//        UILabel *myWarnLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(imageView.frame), SCREEN_WIDTH*0.8, 21)];
//        myWarnLabel.text = @"触发警报";
//        myWarnLabel.textAlignment = NSTextAlignmentCenter;
//        [myView addSubview:myWarnLabel];
//        
//        UILabel *mytitleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(myWarnLabel.frame), SCREEN_WIDTH*0.8, 50)];
//        mytitleLabel.text = @"04:21PM [大厅] 大厅智能灯1报警";
//        mytitleLabel.font = [UIFont systemFontOfSize:12];
//        mytitleLabel.textAlignment = NSTextAlignmentCenter;
//        [myView addSubview:mytitleLabel];
//        self.myCustomAlertView = [CustomAlertView alertViewWithTitle:nil messageView:myView ButtonsWithSureButtonTitle:@"确认" andButtonsWithCancelButtonTitle:@"取消"];
//        self.myCustomAlertView.delegate = self;
//    });
    //注册
    [self.myCollectionView registerNib:[UINib nibWithNibName:@"MILHomePageCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"MILHomePageCollectionViewCell"];
    
    //创建scrollView
//    CGFloat height = (203/320.0)*SCREEN_WIDTH;
//    for (int i = 0; i<3; i++)
//    {
//        UIImageView *myImageView = [[UIImageView alloc]initWithFrame:CGRectMake((SCREEN_WIDTH)*i, 0, SCREEN_WIDTH, height)];
//        myImageView.image = [UIImage imageNamed:@"banner"];
//        [self.myScrollView addSubview:myImageView];
//    }
//    self.myScrollView.pagingEnabled = YES;
//    self.myScrollView.contentSize = CGSizeMake(SCREEN_WIDTH*3, height);
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



#pragma mark -- 获取设备列表
- (void)getUserDeviceList
{
    GetUserDeviceApi *api = [[GetUserDeviceApi alloc]initWithDictionary:@{@"uid":EXRACT_OBJECT(UID),@"token":EXRACT_OBJECT(TOKEN)}];
    [api startWithCompletionAnimation:NO andBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
        NSDictionary * myDic = [request responseJSONObject];
        NSLog(@"my Dic == %@ ",myDic);
        [self.myDataMutableArray removeAllObjects];
        
        if ([myDic[@"errcode"] intValue] == 0) {
            NSArray *returnDataArray = myDic[@"data"];
            for (NSDictionary *dic in returnDataArray) {
                MILUserDeviceModel *model = [[MILUserDeviceModel alloc]init];
                model.ID = dic[@"id"];
                model.device_id = dic[@"device_id"];
                model.mac = dic[@"mac"];
                model.name = dic[@"name"];
                model.is_alert = dic[@"is_alert"];
                model.is_online = dic[@"is_online"];
                model.is_open = dic[@"is_open"];
                [self.myDataMutableArray addObject:model];
                [self checkState];
                [self checkAlertState];
            }
        }else{
            [SVProgressHUD showErrorWithStatus:myDic[@"errmsg"]];
        }

    } backfailure:^(__kindof YTKBaseRequest * _Nonnull request) {
        [SVProgressHUD showErrorWithStatus:@"请求失败"];

    } requestFailure:^(__kindof YTKBaseRequest * _Nonnull request) {
        [SVProgressHUD showErrorWithStatus:@"请求失败"];

    }];
    
    
//    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
//        
//        
//    } failure:^(YTKBaseRequest *request) {
//        
//        [SVProgressHUD showErrorWithStatus:@"请求失败"];
//    }];

}

- (void)checkState{
    for (MILUserDeviceModel *model in self.myDataMutableArray) {
        if ([model.is_alert isEqualToString:@"1"]) {
            self.myWarnBtn.selected = YES;
            return;
        } else {
            self.myWarnBtn.selected = NO;
        }
    }

}

- (void)checkAlertState {
    for (MILUserDeviceModel *model in self.myDataMutableArray) {
        if ([model.is_open isEqualToString:@"1"]) {
            self.myStatusBtn.selected = YES;
            return;
        } else {
            self.myStatusBtn.selected = NO;
        }
    }
}

- (void)checkHomeState {
    NSArray *interfaceNames = CFBridgingRelease(CNCopySupportedInterfaces());
    NSDictionary *SSIDInfo;
    for (NSString *interfaceName in interfaceNames) {
        SSIDInfo = CFBridgingRelease(CNCopyCurrentNetworkInfo((__bridge CFStringRef)interfaceName));
        BOOL isNotEmpty = (SSIDInfo.count > 0);
        if (isNotEmpty) {
            break;
        }
    }
    
    int mode;
    NSString *ssid = [SSIDInfo objectForKey:@"SSID"];
    if ([ssid isEqualToString:EXRACT_OBJECT(SSID)]) { // 在家
        self.myLeaveHomeBtn.selected = YES;
        mode = 0;
    } else { // 离家
        self.myLeaveHomeBtn.selected = NO;
        mode = 1;
    }
    [SetModeApi setMode:mode success:^(NSDictionary *dic) {
        
    } fail:^(NSDictionary *dic) {
        
    }];
    
}

#pragma mark -- 按钮点击
- (void)onLeftButtonClick:(id)sender
{
    //设置界面
    MILSettingViewController *milSettingVC = [[MILSettingViewController alloc]init];
    [self.navigationController pushViewController:milSettingVC animated:YES];
}

#pragma mark -- UIScrollViewDelegate
//-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
//{
//    NSInteger count = (int)(scrollView.contentOffset.x/scrollView.frame.size.width);
//    if (count == 0)
//    {
//        self.myScrollImageView1.image = [UIImage imageNamed:@"lunbohong"];
//        self.myScrollImageView2.image = [UIImage imageNamed:@"lunbo"];
//        self.myScrollImageView3.image = [UIImage imageNamed:@"lunbo"];
//    }
//    else if(count == 1)
//    {
//        self.myScrollImageView1.image = [UIImage imageNamed:@"lunbo"];
//        self.myScrollImageView2.image = [UIImage imageNamed:@"lunbohong"];
//        self.myScrollImageView3.image = [UIImage imageNamed:@"lunbo"];
//    }
//    else if(count == 2)
//    {
//        self.myScrollImageView1.image = [UIImage imageNamed:@"lunbo"];
//        self.myScrollImageView2.image = [UIImage imageNamed:@"lunbo"];
//        self.myScrollImageView3.image = [UIImage imageNamed:@"lunbohong"];
//    }
//    
//}
#pragma mark -- UICollectionViewDelegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    
    return self.myDataArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    MILHomePageCollectionViewCell *cell= [collectionView dequeueReusableCellWithReuseIdentifier:@"MILHomePageCollectionViewCell" forIndexPath:indexPath];
    NSDictionary *dic = self.myDataArray[indexPath.row];
    cell.myImageView.image = [UIImage imageNamed:dic[@"image"]];
    cell.myTitleLabel.text = dic[@"title"];
    
//    if (indexPath.row == 3)
//    {
//        cell.myCloseWarningImageView.hidden = NO;
//    }
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    switch (indexPath.item)
    {
        case 0:
        {
            //  灯泡设置
            MILLightsSettingViewController *milLightsSettingVC = [[MILLightsSettingViewController alloc]init];
            milLightsSettingVC.myDataMutableArray = self.myDataMutableArray;
            [self.navigationController pushViewController:milLightsSettingVC animated:YES];
        }
            break;
        case 1:
        {
            //  场景模式
            MILSelectedDeviceViewController *milSelectedDeviceVC = [[MILSelectedDeviceViewController alloc]init];
            milSelectedDeviceVC.jumpViewControllerFlagString = @"3";
            milSelectedDeviceVC.myDataSourceArray = self.myDataMutableArray;
            [self.navigationController pushViewController:milSelectedDeviceVC animated:YES];

        }
            break;
        case 2:
        {
            //  闹铃设置
            MILSelectedDeviceViewController *milSelectedDeviceVC = [[MILSelectedDeviceViewController alloc]init];
            milSelectedDeviceVC.jumpViewControllerFlagString = @"1";
            milSelectedDeviceVC.myDataSourceArray = self.myDataMutableArray;
            [self.navigationController pushViewController:milSelectedDeviceVC animated:YES];
        }
            break;
        case 3:
        {
            //  雷达预警
            MILRadarWarningViewController *milRadarWarningVC = [[MILRadarWarningViewController alloc]init];
            milRadarWarningVC.myDataSourceArray = self.myDataMutableArray;
            [self.navigationController pushViewController:milRadarWarningVC animated:YES];
        }
            break;

        case 4:
        {
            //  授权权限 先跳转到设备列表界面 并且需要判断这个设备是否有分享权限
            MILSelectedDeviceViewController *milSelectedDeviceVC = [[MILSelectedDeviceViewController alloc]init];
            milSelectedDeviceVC.jumpViewControllerFlagString = @"2";
            milSelectedDeviceVC.myDataSourceArray = self.myDataMutableArray;
            [self.navigationController pushViewController:milSelectedDeviceVC animated:YES];
        }
            break;
        case 5:
        {
            //  商城
            
        }
            break;
            
        default:
            break;
    }
    [collectionView deselectItemAtIndexPath:indexPath animated:NO];
    
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    //此处设置item宽  左右以及中间间距 默认为10
    CGFloat x = ([UIScreen  mainScreen].bounds.size.width-60) /3.0;
    CGFloat y = x*95/80;
    return CGSizeMake(x, y);
}
//
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(15, 15, 8, 15);
}

#pragma mark -- 懒加载
- (NSMutableArray *)myDataArray
{
    if (!_myDataArray)
    {
        _myDataArray = [NSMutableArray array];
        NSArray *arr = @[@{@"title":@"灯泡设置",@"image":@"lightMySetting"},
                         @{@"title":@"场景模式",@"image":@"senceMode"},@{@"title":@"闹铃设置",@"image":@"alarm"},@{@"title":@"雷达预警",@"image":@"radar"},@{@"title":@"授权权限",@"image":@"authorization"},@{@"title":@"商城",@"image":@"mall"}];
        [_myDataArray addObjectsFromArray:arr];
    }
    
    return _myDataArray;
}
//设备列表
- (NSMutableArray *)myDataMutableArray
{
    if (!_myDataMutableArray)
    {
        _myDataMutableArray = [NSMutableArray array];
    }
    
    return _myDataMutableArray;
}

- (SDCycleScrollView *)cycleScrollView
{
    if(!_cycleScrollView)
    {
        UIView *superView = self.topView;
        _cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, 0, 0) delegate:self placeholderImage:[UIImage imageNamed:@"banner"]];
        _cycleScrollView.localizationImageNamesGroup = @[@"banner", @"banner"];
        _cycleScrollView.autoScrollTimeInterval = 5.;// 自动滚动时间间隔
        _cycleScrollView.pageControlAliment = SDCycleScrollViewPageContolAlimentLeft;// 翻页 右下角
        //        _cycleScrollView.titleLabelBackgroundColor = [UIColor whiteColor];// 图片对应的标题的 背景色。（因为没有设标题）
//        _cycleScrollView.pageControlStyle = SDCycleScrollViewPageContolStyleAnimated;
        _cycleScrollView.currentPageDotColor = [UIColor redColor];
//        _cycleScrollView.pageDotColor = [UIColor darkGrayColor];
//        _cycleScrollView.backgroundColor = [UIColor blackColor];
        _cycleScrollView.pageDotImage = [UIImage imageNamed:@"lunbo"];
        _cycleScrollView.currentPageDotImage = [UIImage imageNamed:@"lunbohong"];
        [superView addSubview:_cycleScrollView];
    }
    return _cycleScrollView;
}
@end
